<?php

/* 
 * 管理员用户表
 * @DateTime 2016-01-07 300js
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class AdminUserModel extends db_help
{    
    public $keyFields = 'user_id';//设置主键
    /**登陆COOKIE*/
    private $cookie_name = 'login_cookie';
    public function __construct() {
        parent::__construct();
        $this->table_name = $this->table('admin_user');
        $this->cookie_domain = $_SERVER['HTTP_HOST'];
    }
    public static function load(){
        return new self();
    }
    public function get_list(){
        return $this->getAll();
    }
    /**
     * 獲取 user_id
     * @param string $user_name 用戶名稱
     * @return int 用戶ID
     */
    public function get_user_id($user_name) {
        $where = array(
            'user_name' => $user_name,
        );
        return $this->getOne('user_id', $where);
    }

    /**
     * 判斷是否過期
     * @param string $user_name 用戶名稱
     * @param string $msg 提供的信息
     * @return boolean true過期，false未過期
     */
    public function checkExpire($user_name, &$msg) {
        $info = AdminUserModel::load()->get_info_byname($user_name);
        if($info) {
            //判斷是否為管理員，2判斷是否禁用，3時間是否過期。
            if($info['is_admin'] == 0) {
                if($info['is_use'] == 0) {//停用的帐号
                    $msg = '抱歉，您的帐号已停用';
                    return true;
                } else {
                    $today = time();
                    if($today < $info['start_time']) {
                        $start_str = publicController::load()->timeToStr($info['start_time']);
                        $msg = '抱歉，您的帳號請在' . $start_str .'登陸,方可生效';
                        return true;
                    }
                    elseif($today > $info['end_time']) {
                        $end_str = publicController::load()->timeToStr($info['end_time']);
                        $msg = '抱歉，您的帳號已經在' . $end_str . '已過期,請及時聯繫管理員' ;
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
        $msg = '帳號信息異常~不允許登陸';
        return true;
    }

    /**
     * 获取用户信息　用prepare完成
     * @param string $user_name 用户名称
     * @return array array(user_pass, salt, user_name);
     */
    public function get_user_info($user_name) {
        $result = array();
        $con = $this->getConn();
        if(!$con) {
            return false;
        }
        $stmt = mysqli_stmt_init($this->getConn());
        $sql = 'select user_pass, salt, user_name from ' . $this->table_name . ' where user_name = ?';
        $stmt->prepare($sql);
        $stmt->bind_param('s', $user_name);
        $stmt->execute();
        $stmt->bind_result($pass, $salt, $name);
        while($stmt->fetch()) {
            $result['user_name'] = $name;
            $result['pass'] = $pass;
            $result['salt'] = $salt;
        }
        $stmt->free_result();
        $stmt->close();      
        return $result;
    }

    /**
     * 获取用户的权限列表
     * @param int $user_id 用户ID
     * @return array 一维结果
     */
    public function get_allot($user_id){
        $where = array(
            'user_id' => $user_id,
        );
        return $this->getOne('action_list', $where);
    }
    /**
     * 获取用户的权限数组
     * @param int $user_id 用户ID
     * @param boolean $is_point 默認帶分號,true/false
     * @return boolean|array 数组
     */
    public function get_allot_array($user_id, $is_point = true) {
        $allot = $this->get_allot($user_id);
        if($allot) {
            $allot_arr = explode(',', $allot);
            $allot_new = '';
            foreach ($allot_arr as $_allot) {
                if($is_point) {
                    $allot_new[] = "'{$_allot}'";
                } else {
                    $allot_new[] = "{$_allot}";
                }
                
            }
            return $allot_new;
        }
        return false;
    }
    


    /**
     * 检查email
     * @param type $user_id
     * @param type $user_name
     * @param type $email
     * @return type
     */
    public function check_email($user_id, $user_name, $email) {
        if(empty($email)) {
            return false;
        }
        $sql = 'select * from ' . $this->table_name . ' where email = ' . "'{$email}' ";
        if($user_id > 0) {
            $sql .= ' and user_id != ' . $user_id;
        } elseif(!empty ($user_name)) {
            $sql .= ' and user_name != ' . "'{$user_name}'";
        }
        return $this->result_row($sql);
    }
    /**
     * 检查用户名
     * @param type $user_id
     * @param type $user_name
     * @return type
     */
    public function check_user_name($user_id, $user_name) {
        $sql = 'select * from ' . $this->table_name . ' where user_id != ' . $user_id . ' and user_name=' . "'{$user_name}'";
        return $this->result_row($sql);
    }

    /**
     * 获取用户名称
     * @param type $user_id
     * @return type
     */
    public function get_user_name($user_id) {
        $where = array('user_id' => $user_id);
        return $this->getOne('user_name', $where);
    }
    public function get_info($user_id) {
        $where = array(
            'user_id' => $user_id,
        );
        return $this->getRow(null, $where);
        
    }
    /**
     * 更新用户 
     * @param type $user_id
     * @param type $data
     * @return type
     */
    public function update_user_info($user_id, $data) {
        $where= array('user_id' => $user_id);        
        return $this->update($data, $where);
    }

    /**
     * 获取详情
     * @param type $user_name
     * @return type
     */
    public function get_info_byname($user_name) {
        $where = array(
            'user_name' => $user_name,
        );
        return $this->getRow(null, $where);
    }
    /**
     * 新增用户
     * @param type $data
     * @return boolean
     */
    public function add_user($data) {
        $bool = $this->insert($data);
        if($bool) {
            return $this->insert_id();
        } 
        return false;
    }
    /**
     * 更新用户 状态 
     * @param type $user_id 
     * @param type $is_use 不更新写－1， 是否使用 0停用 1启用
     * @param type $is_del 不更新写－1， 是否删除 0否，1是
     * @return type
     */
    public function update_user($user_id, $is_use = -1, $is_del = -1) {
        $where = array(
            'user_id' => $user_id,
        );
        $data = array();
        if(in_array($is_use, array(0, 1))) {//是否使用 0停用 1启用
            $data['is_use'] = $is_use;
        }
        if(in_array($is_del, array(0, 1))) {//是否删除0否，1是
            $data['is_del'] = $is_del;
        }
        return $this->update($data, $where);
    }
    /**
     * 设置用户SESSION 为空则清除session
     * @param string $username  可选　支持user_name,user_id 自动判断 用户名，可为空则清除session
     * @param int $user_id 可选　用户ID
     * @return boolean
     */
    function set_session($username = '', $user_id = 0)
    {
        if (empty($username))
        {
            $_SESSION = array();
        }
        else
        {
            if($user_id > 0) {
                $row = $this->get_info($user_id);                
            } else{
                $row = $this->get_info_byname($username);
            }
            if ($row)
            {
                $_SESSION['user_id']   = $row['user_id'];
                $_SESSION['user_name'] = $row['user_name'];
                $_SESSION['email']     = $row['email'];
                return true;
            }
        }
        return false;
    }
    /**
     * 设置cookie
     * @param string $username
     * @param boolean $remember
     */
    function set_cookie($username='', $remember= null )
    {
        if (empty($username))
        {
            /* 摧毁cookie */
            $time = time() - 3600; 
            /*清除 login cookie*/
            setCookies($this->cookie_name, '', $time);
            foreach ($_COOKIE as $key => $val) {
                if(is_array($val)) {
                    foreach ($val as $_key => $_val) {
                        setCookies($_key, '', $time);
                    }
                } else {
                    setCookies($key, '', $time);
                }                
            }
        }
        elseif ($remember)
        {
            /* 设置cookie */
            $time = time() + 3600 * 24 * 3;       
            $row = $this->get_info_byname($username);
            if ($row)
            {                
                $user_id = $row['user_id'];
                $salt = ApiBase::load()->get_unique_id();
                $sign = $this->autoLogin_sign($user_id, $salt);
                $cookie_arr = array(
                    'user_id' => $user_id,
                    'salt' => $salt,
                    'sign' => $sign,
                );
                $compress_str = serialize($cookie_arr);
                setCookies($this->cookie_name, $compress_str, $time);                
            }
        }
    }
    public function auto_login(){
        if(isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0) {
            return false;
        }
        $cookie = getCookies($this->cookie_name);
        $cookie_str = stripslashes($cookie);
        $cookie_arr = unserialize($cookie_str);
        if(isset($cookie_arr['user_id'], $cookie_arr['salt'], $cookie_arr['sign'])) {
            $cookie_sign = $cookie_arr['sign'];
            $make_sign = $this->autoLogin_sign($cookie_arr['user_id'], $cookie_arr['salt']);
            if($cookie_sign == $make_sign) {
                $this->set_session('', $cookie_arr['user_id']);                
            }
        }
    }
    /**
     * 自动登陆密钥
     * @param int $user_id 用户名称
     * @return boolean　返回密钥
     */
    public function autoLogin_sign($user_id, $salt) {
        $row = $this->get_info($user_id);
        if($row) {
            $key = get_config_params('key', 'auto_login');
            return md5($user_id . sha1($salt . md5($key)));
        }
        return false;
    }
    /**
     * 獲取is_admin字段
     * @param type $user_id
     * @return type
     */
    public function get_is_admin($user_id) {
        $where = array(
            'user_id' => $user_id,            
        );
        return $this->getOne('is_admin', $where);
        
    }
}

